<template>
  <ul>
    <transition-group name="list">
      <MainItem v-for="todo in todoList" :key="todo.id" :todo="todo" />
    </transition-group>
  </ul>
</template>

<script>
import MainItem from "./MainItem.vue";
import moment from 'moment'
export default {
  name: "todo-main",
  components: {
    MainItem,
  },
  //组件的响应式数据
  data() {
    return {
      todoList:  JSON.parse(localStorage.getItem("todos")) || [],
    };
  },
  watch:{
    todoList:{
      deep:true,
      immediate:true,
      handler(newVal){
        //存储数据
        localStorage.setItem('todos',JSON.stringify(newVal))
        this.$bus.$emit('todoList',newVal)
      }
    }
  },
  methods: {
    //添加todo
    addTodo(name) {
      this.todoList.push({
        id: `00${this.todoList.length + 1}`,
        name,
        done: false,
        time:moment().format("YYYY-MM-DD HH:mm")
      });
    },
    //单选按钮
    checkDone(id) {
      this.todoList.map((item) => {
        item.id === id ? (item.done = !item.done) : null;
        return item;
      });
    },
    //删除按钮
    deletetodo(id){
     this.todoList = this.todoList.filter(item => item.id!==id)
    },
    //全选/全不选
    allCheck(done){
      this.todoList = this.todoList.map(item=> ({...item,done}))
    },
    //删除已完成
    deleteDone(){
      this.todoList = this.todoList.filter(item =>item.done!==true)
    }

  },
  mounted() {
    //添加todo
    this.$bus.$on("addTodo", this.addTodo);
    //单选checkbox
    this.$bus.$on("checkDone", this.checkDone);
    //删除按钮
    this.$bus.$on("deletetodo",this.deletetodo)
    //全选
    this.$bus.$on("allCheck",this.allCheck)
    //删除已完成
    this.$bus.$on("deleteDone",this.deleteDone)
  }, 
};
</script>

<style scoped>
ul {
  list-style: none;
  margin-top: 10px;
}
.list-enter,
.list-leave-to {
  transform: translateX(150px);
  opacity: 0;
}
.list-enter-to,
.list-leave {
  transform: translateX(0);
  opacity: 1;
}
.list-enter-active,
.list-leave-active {
  transition: all 0.5s linear;
}
</style>